// directives/vDebounce.ts

import { debounce } from '@/utils/debounce';
import type { DirectiveBinding } from 'vue';

export default {
    mounted(el: HTMLElement & { _debouncedHandler?: (e: Event) => void }, binding: DirectiveBinding) {
        const { value, arg } = binding;
        const delay = arg ? parseInt(arg) : 500; // 默认延迟时间

        // 检查是否绑定了函数
        if (typeof value !== 'function') {
            throw new Error('v-debounce directive requires a handler function');
        }

        // 防抖处理后的点击事件处理程序
        el._debouncedHandler = debounce(value, delay);

        // 添加点击事件监听器
        el.addEventListener('click', el._debouncedHandler);
    },
    beforeUnmount(el: HTMLElement & { _debouncedHandler?: (e: Event) => void }) {
        // 移除点击事件监听器
        if (el._debouncedHandler) {
            el.removeEventListener('click', el._debouncedHandler);
        }
    }
};